function D = cvc_eeglab2spm(EEG,condlabels)
% cvc_eeglab2spm - Convert EEGLAB structure to SPM8 meeg object
%
% synopsis:
%
%   D = cvc_eeglab2spm(EEG)
%   D = cvc_eeglab2spm(EEG,condlabelfile)
%
% input:
%
%        EEG : EEGLAB structure with the '.cvc' field (see CVC_LOAD_BDF).
%   condlabel: Cell-array with labels for the trials.
%              If condlabels is not specified all conditions will appear as
%              'Undefined'.
%
% output:
%
%     D : The SPM8 meeg object
%   One dat and mat files written to the disc. The filenames are
%   similar to the EEGLAB files but with an extension '_spm8' denoting that
%   the files are now compatible with SPM8.
%   
% Author: Carsten Stahlhut, 2009

cpwd = pwd;
keyboard
[pathstr,fname] = fileparts(fullfile(EEG.filepath,EEG.filename));
eeglab_fname = fullfile(pathstr,fname);
spm_fname = [fname '_spm8'];

cd(pathstr)

S = [];
S.dataset = [eeglab_fname '.set'];
S.outfile = spm_fname;
% chanlocs = squeeze(struct2cell(EEG.chanlocs));
% S.channels = chanlocs(1,:)';     %EEG.chanlocs.labels is located at position 1
S.channels = 'all';
S.usetrials = 1;
S.conditionlabel = {'Undefined'};
S.continuous = 0;
S.usetrials = 1;
S.save = 0;
D = spm_eeg_convert(S);
save(D)


S = [];
S.task = 'settype';
S.D = [spm_fname '.mat'];
S.ind = 1:EEG.nbchan;
S.type = 'EEG';
S.save = 1;
D = spm_eeg_prep(S);
save(D);


%% Add condition labels
if nargin>1
%     D = conditions(D, [], importdata(condlabelfile));
    D = conditions(D, [], condlabels);
else
    try
        D.cvc.event = EEG.event;
        D.cvc.epoch = EEG.epoch;
%         for i=1:D.ntrials, condlabels{i} = num2str(EEG.epoch(i).eventTrialType1_8{1}); end
%         D = conditions(D, [], condlabels);
%         D = conditions(D, [], {EEG.epoch.eventtype});
        disp('No labels for trials loaded - default is Undefined')
    catch
        disp('No labels for trials loaded - default is Undefined')
    end
end
save(D)


%% Load sensor positions
S = [];
try
    S.sensfile = [EEG.cvc.locsfile '.mat'];
catch
    disp(['No locsfile specified in EEG.cvc structure. ',...
        'Select file with sensor positions...'])
    S.sensfile = spm_select(1,'.mat',...
        'Select mat-file with sensor positions');
end
S.source = 'mat';
try
    S.headshapefile = [EEG.cvc.fidsfile '.mat'];
catch
    disp(['No fiducials file specified in EEG.cvc structure. ',...
        'Select file with fiducials positions...'])
    S.headshapefile = spm_select(1,'.mat',...
        'Select mat-file with fiducials nas/lpa/rpa positions');
end
S.fidlabel = [];
try
    for i=1:length(EEG.cvc.elpfidlocs)
        fidlabels = EEG.cvc.elpfidlocs(i).labels;
        switch fidlabels
            case 'Nz'
                S.fidlabel = [S.fidlabel 'nas '];
            case {'LPA','RPA'}
                S.fidlabel = [S.fidlabel lower(fidlabels) ' '];
            otherwise
                disp('Only Nz, LPA, and RPA are supported as fiducials at this time.')
        end
    end
    S.fidlabel(end) = [];       %Delete the last space introduced   
catch
    S.fidlabel = 'nas lpa rpa';
end
S.D = [spm_fname '.mat'];
S.task = 'loadeegsens';
S.save = 0;
D = spm_eeg_prep(S);
save(D)


%Do hack such that transformation of sensors can be performed in
%transform_sens.m (relevant when performing co-registration)
dummy = D.sensors('EEG');
dummy.type = 'eeg';
D = D.sensors('EEG',dummy);
clear dummy
save(D)

cd(cpwd)